<style>
.gy-view {
  background: #fff;
  height: 100%;
}

.table-box {
  display: flex;
  align-items: flex-start;
  height: calc(100% - 100px);
}

.table-box>.vxe-table {
  flex: 1;
  width: 200px;
}

.budget-table-all {}

.el-tabs__active-bar {
  width: 42px !important;
}
</style>
<template>
  <div class="gy-view">
    <el-tabs v-model="activeName" style="padding: 10px 0;">
      <el-tab-pane label="总预算" name="XMJFLY_ZYS"></el-tab-pane>
      <el-tab-pane label="纵向" name="XMJFLY_ZX" v-if="budget_from.includes('XMJFLY_ZX')"></el-tab-pane>
      <el-tab-pane label="横向" name="XMJFLY_HX" v-if="budget_from.includes('XMJFLY_HX')"></el-tab-pane>
      <el-tab-pane label="自筹" name="XMJFLY_ZC" v-if="budget_from.includes('XMJFLY_ZC')"></el-tab-pane>
    </el-tabs>
    <vxe-button status="primary" content="选择科目" size="mini" @click="showSelectSubject"
      v-if="activeName != 'XMJFLY_ZYS' && isEdit" style="margin-bottom: 10px;"></vxe-button>
    <div class="table-box" v-if="loadingTbale && activeName != 'XMJFLY_ZYS'">
      <vxe-table height="auto" border resizable show-overflow :data="tableData"
        :edit-config="{ trigger: 'click', mode: 'row', showIcon: false, enabled: isEdit }" size="mini" ref="myVxeTable">
        <vxe-column type="seq" width="60" fixed="left"></vxe-column>
        <vxe-column align="left" field="class_funds" title="科目名称" min-width="100" fixed="left"></vxe-column>
        <vxe-column field="pro_member_org_name" title="承制部门" min-width="100" fixed="left"></vxe-column>
        <vxe-column field="total" title="科目合计" min-width="100" fixed="left">
          <template #default="{ row }">
            <span>{{ total(row.budget_template_id) }}</span>
          </template>
        </vxe-column>
        <template v-for="(item, index) in yearList">
          <vxe-column v-if="(activeName == item.budget_source_id || activeName == 'XMJFLY_ZYS') && isShow"
            :field="item.pl_pro_year" :key="index" :title="item.pl_pro_year" min-width="240" :edit-render="{}">
            <template #header>
              <span>{{ item.pl_pro_year }}</span>
              <vxe-button type="text" status="primary" icon="vxe-icon-delete" v-if="isEdit"
                @click="showDelYear(index)"></vxe-button>
              <vxe-button type="text" status="primary" icon="vxe-icon-edit" v-if="isEdit"
                @click="showEditYear(item)"></vxe-button>
            </template>
            <template #default="{ row }">
              <span v-if="item.budgetAccount[row.budget_template_id]">{{
                item.budgetAccount[row.budget_template_id].year_budget }}</span>
            </template>
            <template #edit="{ row }">
              <template>
                <vxe-input v-if="item.budgetAccount[row.budget_template_id]"
                  v-model="item.budgetAccount[row.budget_template_id].year_budget" type="float" step="1" maxlength="12"
                  clearable></vxe-input>
              </template>

            </template>
          </vxe-column>
        </template>
        <vxe-column title="操作" width="100" fixed="right" v-if="isEdit">
          <template #default="{ row }">
            <template>
              <vxe-button @click="showDelSubject(row)" size="mini">删除</vxe-button>
            </template>
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-button type="text" icon="vxe-icon-add" @click="showAddYear" v-if="isEdit && isYearShow()"></vxe-button>
    </div>
    <div class="budget-table-all" v-if="activeName == 'XMJFLY_ZYS'">
      <div v-for="(item, index) in budget_from" :key="index">
        <span>{{ activeObj[item] }}</span>
        <vxe-table style="margin-top: 10px;" height="200" border resizable show-overflow :data="tableList(item)"
          size="mini" ref="myVxeTable">
          <vxe-column type="seq" width="60" fixed="left"></vxe-column>
          <vxe-column field="class_funds" title="科目名称" min-width="100" fixed="left"></vxe-column>
          <vxe-column v-for="(column, index) in tableColumn(item)" :key="index" :field="column.pro_member_org_name"
            :title="column.pro_member_org_name">
            <template #default="{ row }">
              <span>{{ deptTotal(row, column, item) }}</span>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <el-empty description="暂无数据" v-if="!budget_from.length"></el-empty>

    </div>

    <el-dialog :title="'新增'" :visible.sync="dialogFormVisible" v-if="dialogFormVisible">
      <el-form :model="yearForm" :rules="rules" ref="ruleForm">
        <el-form-item label="年度" prop="pl_pro_year">
          <el-date-picker value-format="yyyy" size="mini" v-model="yearForm.pl_pro_year" type="year" style="width: 160px"
            placeholder="选择年">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="saveYear" size="mini">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template> 
<script>

export default {
  name: "PLANS",
  data() {
    return {
      loadingTbale: true,
      activeName: 'XMJFLY_ZYS',
      budgetList: [],
      yearList: [],
      budget_from: [],
      activeObj: {
        XMJFLY_ZYS: '总预算',
        XMJFLY_ZX: '纵向',
        XMJFLY_HX: '横向',
        XMJFLY_ZC: '自筹',
      },
      isShow: true,
      dialogFormVisible: false,
      yearForm: {
        pl_pro_year: ''
      },
      rules: {
        pl_pro_year: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
      },
      userDept: '',
      isEdit: false
    }
  },
  mounted() {
    this.init()
  },
  computed: {
    tableData() {
      if (this.activeName == 'XMJFLY_ZYS') {
        return this.budgetList
      }
      return this.budgetList.filter((item) => {
        return item.budget_source_id == this.activeName
      })
    }
  },
  watch: {
    yearList: {
      handler() {
        this.hehaiyang()
      },
      deep: true
    }
  },
  methods: {
    // 初始化 通过自动化获取数据 并且构建可编辑数据
    async init() {
      this.isEdit = await window.customFieldService.isFieldEditable('pl_pro_budgrt')
      console.log(this.isEdit)
      this.first = true
      let _this = this
      window.eventService.onEvent('field-change', async () => {
        let records = await window.customFieldService.getRecord()
        if (records.budget_from.length !== _this.budget_from.length) {
          this.activeName = 'XMJFLY_ZYS'
        }
        _this.budget_from = records.budget_from
      })
      window.eventService.onEvent('record-reload', async () => {
        _this.loadingTbale = false
        setTimeout(async () => {
          let records = await window.customFieldService.getRecord()
          if (records.pl_pro_budgrt) {
            _this.first = true
            _this.initData(records)
          }
        }, 500)
      })
      setTimeout(async () => {
        let records = await window.customFieldService.getRecord()
        this.initData(records)
      }, 500)
    },
    initData(records) {
      this.budget_from = records.budget_from
      let yearList = []
      let budgetList = []
      console.log(records.pl_pro_budgrt)
      records.pl_pro_budgrt.forEach((item) => {
        let a1 = yearList.findIndex((findItem) => {
          return (findItem.pl_pro_year_id == item.pl_pro_year_id && findItem.budget_source_id == item.budget_source_id)
        })
        if (a1 == -1) {
          yearList.push(item)
        }
        let a2 = budgetList.findIndex((findItem) => {
          return (findItem.budget_template_id == item.budget_template_id && findItem.budget_source_id == item.budget_source_id)
        })
        if (a2 == -1 && item.budget_template_id) {
          budgetList.push(item)
        }
      })
      yearList.forEach((yearItem) => {
        if (!yearItem.budgetAccount) {
          yearItem.budgetAccount = {}
        }
        budgetList.forEach((item) => {
          if (yearItem.budget_source_id == item.budget_source_id) {
            if (!yearItem.budgetAccount[item.budget_template_id]) {
              let findData = records.pl_pro_budgrt.find((findItem) => {
                return findItem.budget_template_id == item.budget_template_id && findItem.budget_source_id == item.budget_source_id && findItem.pl_pro_year == yearItem.pl_pro_year
              })
              yearItem.budgetAccount[item.budget_template_id] = {
                year_budget: findData.year_budget,
                budget_template_id: item.budget_template_id,
                budget_source_id: item.budget_source_id,
                budget_source_name: item.budget_source_name,
                class_funds: item.class_funds,
                pro_member_org_name: item.pro_member_org_name,
                pro_member_org_id: item.pro_member_org_id
              }
            }
          }
        })
      })
      this.yearList = yearList
      this.budgetList = budgetList
      this.loadingTbale = true
    },
    tableList(type) {
      if (!type) {
        return []
      }
      return this.budgetList.filter((item) => {
        return item.budget_source_id == type
      })
    },
    tableColumn(type) {
      if (!type) {
        return []
      }
      let list = this.budgetList.filter((item) => {
        return item.budget_source_id == type
      })
      let column = []
      list.forEach((item) => {
        let is = column.findIndex((findItem) => {
          return findItem.pro_member_org_id == item.pro_member_org_id
        })
        if (is == -1) {
          column.push({
            pro_member_org_id: item.pro_member_org_id,
            pro_member_org_name: item.pro_member_org_name
          })
        }
      })
      return column
    },
    // 选择科目
    showSelectSubject() {
      let list = this.budgetList.filter((item) => {
        return item.budget_source_id == this.activeName
      })
      window.systemService.callAutomatic({
        automaticId: 'budget_choose',
        args: [list.map((item) => item.budget_template_id)]
      }).then(async (result) => {
        result.returnValue.forEach((item) => {
          item.budget_source_name = this.activeObj[this.activeName]
          item.budget_source_id = this.activeName
        })
        this.budgetList = [...this.budgetList, ...result.returnValue]
        this.loadingTbale = false
        setTimeout(() => {
          this.loadingTbale = true
        }, 10);
        this.setEditTableData()
      })
    },
    // 添加年份
    showAddYear() {
      this.yearForm.pl_pro_year = ''
      this.yearForm.isType = 'add'
      this.dialogFormVisible = true
    },
    showDelYear(index) {
      //调用确认提示
      window.systemService.confirm({
        title: '此操作将永久删除，是否继续?'
      }).then(confirm => {
        if (!confirm) {
          return;
        }
        this.isShow = false
        this.yearList.splice(index, 1)
        setTimeout(() => {
          this.isShow = true
        }, 100)
      });

    },
    showEditYear(item) {
      this.yearForm.pl_pro_year = item.pl_pro_year
      this.yearForm.pl_pro_year_id = item.pl_pro_year_id
      this.yearForm.isType = 'edit'
      this.dialogFormVisible = true
    },
    saveYear() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          return
        }
        let ylist = this.yearList.filter((item) => {
          return item.budget_source_id == this.activeName
        })
        console.log(ylist)
        if (this.yearForm.isType == 'add') {
          let isEmpty = ylist.findIndex((item) => {
            return item.pl_pro_year == this.yearForm.pl_pro_year
          })
          if (isEmpty != -1) {
            this.$message('已存在选择年份')
            return
          }
          let yearObj = {
            pl_pro_year: this.yearForm.pl_pro_year,
            pl_pro_year_id: '' + this.yearList.length + new Date().getTime(),
            budget_source_name: this.activeObj[this.activeName],
            budget_source_id: this.activeName,
            pro_member_org_id: this.userDept
          }
          this.yearList.push(yearObj)
          this.setEditTableData()
        } else {
          let isEdit = true
          ylist.forEach((item) => {
            if (item.pl_pro_year == this.yearForm.pl_pro_year && item.pl_pro_year_id != this.yearForm.pl_pro_year_id) {
              isEdit = false
            }
          })
          if (!isEdit) {
            this.$message('已存在选择年份')
            return
          }
          this.yearList.forEach((item) => {
            if (item.pl_pro_year_id == this.yearForm.pl_pro_year_id) {
              item.pl_pro_year = this.yearForm.pl_pro_year
            }
          })
        }
        this.dialogFormVisible = false
      });
    },

    // 设置可编辑数据
    setEditTableData() {
      let list = JSON.parse(JSON.stringify(this.yearList))
      list.forEach((yearItem) => {
        if (!yearItem.budgetAccount) {
          yearItem.budgetAccount = {}
        }
        this.budgetList.forEach((item) => {
          if (yearItem.budget_source_id == item.budget_source_id) {
            if (!yearItem.budgetAccount[item.budget_template_id]) {
              yearItem.budgetAccount[item.budget_template_id] = {
                year_budget: '',
                budget_template_id: item.budget_template_id,
                budget_source_id: item.budget_source_id,
                budget_source_name: item.budget_source_name,
                class_funds: item.class_funds,
                pro_member_org_name: item.pro_member_org_name,
                pro_member_org_id: item.pro_member_org_id
              }
            }
          }
        })
      })
      this.yearList = list
    },
    // 保存
    hehaiyang() {
      let budgetList = []
      if (this.yearList.length) {
        this.yearList.forEach((yearItem) => {
          if (yearItem.budgetAccount && Object.keys(yearItem.budgetAccount).length) {
            for (const key in yearItem.budgetAccount) {
              budgetList.push(Object.assign(yearItem.budgetAccount[key], {
                pl_pro_year: yearItem.pl_pro_year,
                pl_pro_year_id: yearItem.pl_pro_year_id
              }))
            }
          } else {
            budgetList.push(yearItem)
          }
        })
      }
      this.budgetList.forEach((item) => {
        let fIndex = this.yearList.findIndex((findItem) => {
          return findItem.budget_source_id == item.budget_source_id
        })
        if (fIndex == -1) {
          let pushItem = JSON.parse(JSON.stringify(item))
          pushItem.pl_pro_year = ''
          pushItem.pl_pro_year_id = ''
          pushItem.year_budget = ''
          budgetList.push(pushItem)
        }
      })
      if (this.first) {
        this.first = false
        return
      }
      window.customFieldService.setFieldValue({
        field: 'pl_pro_budgrt',
        value: budgetList
      })
    },
    total(budget_template_id) {
      let total = 0
      this.yearList.forEach((item) => {
        if (item.budgetAccount && item.budget_source_id == this.activeName) {
          total += +item.budgetAccount[budget_template_id].year_budget
        }
      })
      return total
    },
    deptTotal(row, item, type) {
      let ylist = this.yearList.filter((f) => {
        return type == f.budget_source_id
      })
      let total = 0
      ylist.forEach((f) => {
        total += +f.budgetAccount[row.budget_template_id].year_budget
      })

      return total
    },
    showDelSubject(row) {
      //调用确认提示
      window.systemService.confirm({
        title: '此操作将永久删除，是否继续?'
      }).then(confirm => {
        if (!confirm) {
          return;
        }
        let list = JSON.parse(JSON.stringify(this.yearList))
        this.budgetList = this.budgetList.filter((item) => {
          return !(item.budget_template_id == row.budget_template_id && item.budget_source_id == this.activeName)
        })
        list.forEach((item) => {
          if (item.budgetAccount[row.budget_template_id]) {
            delete item.budgetAccount[row.budget_template_id]
          }
        })
        this.yearList = list
      });
    },
    isYearShow() {
      let fList = this.yearList.filter((item) => {
        return item.budget_source_id == this.activeName
      })
      if (fList.length < 10) {
        return true
      } else {
        return false
      }
    }
  },


}
</script>
